package com.ksxy.afingerprint.utils

import android.app.KeyguardManager
import android.content.Context
import android.hardware.fingerprint.FingerprintManager
import android.os.Build
import android.support.annotation.NonNull
import com.ksxy.afingerprint.R
import java.lang.IllegalArgumentException

/**
 *  author : chenyinying
 *  e-mail : me@korion.cn
 *  time   : 2018/07/06
 *  desc   :
 *  version: 1.0
 */
 object EnvUtils{

    const val CODE_FINGER_PRINT_AUTH_OK = 0
    const val CODE_HARDWARE_NOT_DETECTED = 1
    const val CODE_NO_ENROLLED_FINGERPRINT = 2
    const val CODE_SDK_INT_BELOW_M = 3
    const val CODE_KEYGUARD_NO_SECURE = 4
    private val mCodeMap = mutableMapOf<Int, String>()
    private var inited = false

    fun init(context: Context){
        mCodeMap.put(EnvUtils.CODE_FINGER_PRINT_AUTH_OK, context.getString(R.string.finger_print_auth_ok))
        mCodeMap.put(EnvUtils.CODE_HARDWARE_NOT_DETECTED, context.getString(R.string.hardware_not_detected))
        mCodeMap.put(EnvUtils.CODE_NO_ENROLLED_FINGERPRINT, context.getString(R.string.no_enrolled_fingerprint))
        mCodeMap.put(EnvUtils.CODE_SDK_INT_BELOW_M, context.getString(R.string.sdk_int_below_m))
        mCodeMap.put(EnvUtils.CODE_KEYGUARD_NO_SECURE, context.getString(R.string.keyguard_no_secure))
        inited = true
    }

    fun checkSupportFingerPrintAuth(@NonNull context: Context): Int{
        hasInited()
        if(context == null){
            throw IllegalArgumentException("context must be no-null")
        }
        if(Build.VERSION.SDK_INT < Build.VERSION_CODES.M){
            return CODE_SDK_INT_BELOW_M
        }
        val fingerprintManager = context.getSystemService(FingerprintManager::class.java)
        if(!fingerprintManager.isHardwareDetected){
            return CODE_HARDWARE_NOT_DETECTED
        }

        if (!fingerprintManager.hasEnrolledFingerprints()){
            return CODE_NO_ENROLLED_FINGERPRINT
        }

        val keyguardManager = context.getSystemService(KeyguardManager::class.java)
        if (!keyguardManager.isKeyguardSecure){
            return CODE_KEYGUARD_NO_SECURE
        }
        return CODE_FINGER_PRINT_AUTH_OK
    }

    fun getCheckResultDesc(resultCode: Int): String? {
        return mCodeMap[resultCode]
    }

    private fun hasInited(){
        if(!inited){
            throw IllegalAccessException("Please invoke init() before")
        }
    }
}